package com.team9.fitness.service;

import com.team9.fitness.entity.PostFavorite;
import com.team9.fitness.mapper.PostFavoriteMapper;
import com.team9.fitness.mapper.CommunityPostMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 帖子喜欢服务类
 * 
 * 提供帖子喜欢相关的业务逻辑：
 * - 喜欢管理：喜欢、取消喜欢
 * - 状态查询：查询用户喜欢状态
 * - 统计功能：统计帖子喜欢数量
 * - 事务管理：确保数据一致性
 */
@Slf4j
@Service
public class PostFavoriteService {

    @Autowired
    private PostFavoriteMapper postFavoriteMapper;

    @Autowired
    private CommunityPostMapper communityPostMapper;

    /**
     * 喜欢帖子
     */
    @Transactional
    public boolean favoritePost(Long userId, Long postId) {
        try {
            // 检查是否已经喜欢
            PostFavorite existingFavorite = postFavoriteMapper.selectByUserIdAndPostId(userId, postId);
            
            if (existingFavorite != null && existingFavorite.getIsFavorited()) {
                log.warn("用户已经喜欢过该帖子: userId={}, postId={}", userId, postId);
                return false;
            }

            // 创建或更新喜欢记录
            PostFavorite postFavorite = PostFavorite.builder()
                    .userId(userId)
                    .postId(postId)
                    .isFavorited(true)
                    .build();
            postFavorite.setCreatedAtIfNull();

            int result = postFavoriteMapper.insertOrUpdate(postFavorite);
            if (result > 0) {
                // 更新帖子喜欢数量
                int favoriteCount = postFavoriteMapper.countFavoritesByPostId(postId);
                communityPostMapper.updateFavoriteCount(postId, favoriteCount);
                
                log.info("帖子喜欢成功: userId={}, postId={}, favoriteCount={}", userId, postId, favoriteCount);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("帖子喜欢失败: userId={}, postId={}", userId, postId, e);
            return false;
        }
    }

    /**
     * 取消喜欢帖子
     */
    @Transactional
    public boolean unfavoritePost(Long userId, Long postId) {
        try {
            // 检查是否已经喜欢
            PostFavorite existingFavorite = postFavoriteMapper.selectByUserIdAndPostId(userId, postId);
            
            if (existingFavorite == null || !existingFavorite.getIsFavorited()) {
                log.warn("用户未喜欢该帖子: userId={}, postId={}", userId, postId);
                return false;
            }

            // 更新喜欢状态为false
            int result = postFavoriteMapper.updateFavoriteStatus(userId, postId, false);
            if (result > 0) {
                // 更新帖子喜欢数量
                int favoriteCount = postFavoriteMapper.countFavoritesByPostId(postId);
                communityPostMapper.updateFavoriteCount(postId, favoriteCount);
                
                log.info("帖子取消喜欢成功: userId={}, postId={}, favoriteCount={}", userId, postId, favoriteCount);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("帖子取消喜欢失败: userId={}, postId={}", userId, postId, e);
            return false;
        }
    }

    /**
     * 切换帖子喜欢状态
     */
    @Transactional
    public boolean togglePostFavorite(Long userId, Long postId) {
        try {
            PostFavorite existingFavorite = postFavoriteMapper.selectByUserIdAndPostId(userId, postId);
            
            if (existingFavorite != null && existingFavorite.getIsFavorited()) {
                // 如果已喜欢，则取消喜欢
                return unfavoritePost(userId, postId);
            } else {
                // 如果未喜欢，则喜欢
                return favoritePost(userId, postId);
            }
        } catch (Exception e) {
            log.error("切换帖子喜欢状态失败: userId={}, postId={}", userId, postId, e);
            return false;
        }
    }

    /**
     * 获取用户喜欢状态
     */
    public Boolean getUserFavoriteStatus(Long userId, Long postId) {
        try {
            PostFavorite postFavorite = postFavoriteMapper.selectByUserIdAndPostId(userId, postId);
            return postFavorite != null ? postFavorite.getIsFavorited() : false;
        } catch (Exception e) {
            log.error("获取用户喜欢状态失败: userId={}, postId={}", userId, postId, e);
            return false;
        }
    }

    /**
     * 获取帖子喜欢数量
     */
    public int getPostFavoriteCount(Long postId) {
        try {
            return postFavoriteMapper.countFavoritesByPostId(postId);
        } catch (Exception e) {
            log.error("获取帖子喜欢数量失败: postId={}", postId, e);
            return 0;
        }
    }

    /**
     * 获取用户喜欢的帖子列表
     */
    public List<PostFavorite> getUserFavoritedPosts(Long userId) {
        try {
            return postFavoriteMapper.selectFavoritedByUserId(userId);
        } catch (Exception e) {
            log.error("获取用户喜欢帖子列表失败: userId={}", userId, e);
            return List.of();
        }
    }

    /**
     * 获取帖子喜欢用户列表
     */
    public List<PostFavorite> getPostFavoritedUsers(Long postId) {
        try {
            return postFavoriteMapper.selectFavoritedByPostId(postId);
        } catch (Exception e) {
            log.error("获取帖子喜欢用户列表失败: postId={}", postId, e);
            return List.of();
        }
    }
}
